﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using DTO;
using BLL;

namespace HDT.GUI
{
    public partial class FrmGioHang : Form
    {        
        private string PRODUCT_IMAGE_FOLDER = "Image\\_Product\\";
        private List<ChiTietHoaDonDTO> dsChiTiet;    
        private HoaDonDTO hoaDonTam;

        public delegate bool MyDelegete(ChiTietHoaDonDTO chiTiet);
        public MyDelegete UpdateChiTiet;
        public MyDelegete RemoteChiTiet;
        public delegate void DelegateSetInfo(String TenKH, string DT, DateTime NgayLap);
        public DelegateSetInfo SetHoaDon;
        public delegate void DelegateReset();
        public DelegateReset ResetAll;
        public DelegateReset RemoveAll;

        public FrmGioHang()
        {
            InitializeComponent(); 
            dsChiTiet = new List<ChiTietHoaDonDTO>();
            hoaDonTam = new HoaDonDTO();
        }

        public FrmGioHang(HoaDonDTO hoaDonTam, List<ChiTietHoaDonDTO> dsChiTiet)
            : this()
        {
            // TODO: Complete member initialization
            this.hoaDonTam = hoaDonTam;
            this.dsChiTiet = dsChiTiet;
        }

        private void btnQuayLai_Click(object sender, EventArgs e)
        {
            this.Dispose();
        }

        private void ShowDetail()
        {
            dgvGioHang.Rows.Clear();
            int GiaTri = 0;
            int length = dsChiTiet.Count;
            for (int i = 0; i < length; i++)
            {
                DataGridViewRow row = (DataGridViewRow)dgvGioHang.Rows[0].Clone();
                row.Cells[0].Value = new MatHangBLL().GetByID(dsChiTiet[i].MaMatHang).MaMatHang;
                row.Cells[1].Value = new MatHangBLL().GetByID(dsChiTiet[i].MaMatHang).TenMatHang;
                row.Cells[2].Value = new MatHangBLL().GetByID(dsChiTiet[i].MaMatHang).DonViTinh;
                row.Cells[3].Value = dsChiTiet[i].SoLuong.ToString("#,##0");
                dgvGioHang.Rows.Add(row);                
                double CK = new ChiTietHoaDonBLL().GetChietKhau(dsChiTiet[i]);
                int DonGia = new ChiTietHoaDonBLL().GetDonGia(dsChiTiet[i]);
                dsChiTiet[i].DonGiaBan = DonGia;
                dsChiTiet[i].ChietKhau = CK;
                GiaTri += (int)(dsChiTiet[i].SoLuong * dsChiTiet[i].DonGiaBan * (1 - dsChiTiet[i].ChietKhau));
            }
            lblTCGia.Text = GiaTri.ToString("#, ##0");
        }

        private void UpdateCT(ChiTietHoaDonDTO chiTiet)
        {
            if (UpdateChiTiet(chiTiet))
            {
                ShowDetail();
                btnDelete.Enabled = true;
                btnEdit.Enabled = false;
            }
        }

        private void RemoveCT(ChiTietHoaDonDTO chiTiet)
        {
            if (RemoteChiTiet(chiTiet))
            {
                ShowDetail();
            }
        }

        private void LoadProductImage(string filename)
        {
            try
            {
                string path = PRODUCT_IMAGE_FOLDER + filename;
                Image img = Image.FromFile(path);
                picMH.Image = img;
            }
            catch (Exception)
            {
                picMH.Image = null;
            }
        }

        private void LoadCTHDInfo(ChiTietHoaDonDTO chiTiet)
        {
            try
            {
                MatHangDTO matHang = new MatHangBLL().GetByID(chiTiet.MaMatHang);
                txtTenMH.Text = matHang.TenMatHang;
                lblMaMH.Text = chiTiet.MaMatHang;
                txtGia.Text = new MatHangBLL().DonGiaBan(matHang.MaMatHang).ToString("#,##0");
                txtSLTon.Text = new MatHangBLL().SoLuongTon(matHang.MaMatHang).ToString("#,##0");
                LoadProductImage(matHang.HinhAnh);
                numSL.Enabled = true;
                numSL.Value = chiTiet.SoLuong;
                btnDelete.Enabled = true;                
            }
            catch
            {
                txtTenMH.Text = "## Unknown ##";
                txtGia.Text = "N/A";
                txtSLTon.Text = "N/A";
                picMH.Image = null;
                numSL.Enabled = false;
                btnDelete.Enabled = false;
            }
            btnEdit.Enabled = false;
        }

        private void btnEdit_Click(object sender, EventArgs e)
        {
            try
            {
                ChiTietHoaDonDTO ct = new ChiTietHoaDonDTO();
                ct.MaMatHang = lblMaMH.Text;
                ct.SoLuong = (short)numSL.Value;
                UpdateCT(ct);
            }
            catch
            {
            }
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            try
            {
                ChiTietHoaDonDTO ct = new ChiTietHoaDonDTO();
                ct.MaMatHang = lblMaMH.Text;
                ct.SoLuong = (short)numSL.Value;
                RemoveCT(ct);
            }
            catch
            {
            }
        }

        private void numSL_ValueChanged(object sender, EventArgs e)
        {
            btnDelete.Enabled = false;
            btnEdit.Enabled = true;
            try
            {
                ChiTietHoaDonDTO ct = new ChiTietHoaDonDTO();
                ct.MaMatHang = lblMaMH.Text;
                ct.SoLuong = (short)numSL.Value;
                txtCK.Text = new ChiTietHoaDonBLL().GetChietKhau(ct).ToString("#,##0.000 %");
            }
            catch
            {
                txtCK.Text = "N/A";
            }
        }

        private void FrmGioHang_Load(object sender, EventArgs e)
        {
            txtNV.Text = hoaDonTam.MaNhanVien;
            ShowDetail();
        }

        private void dgvGioHang_SelectionChanged(object sender, EventArgs e)
        {
            if (dgvGioHang.SelectedRows.Count > 0)
            {
                try
                {
                    string MaMH = dgvGioHang.SelectedRows[0].Cells[0].Value.ToString();
                    foreach (ChiTietHoaDonDTO chiTiet in dsChiTiet)
                    {
                        if (chiTiet.MaMatHang == MaMH)
                        {
                            LoadCTHDInfo(chiTiet);
                            return;
                        }
                    }
                }
                catch
                {
                    LoadCTHDInfo(null);
                }
            }
        }
        
        private void txt_TextChanged(object sender, EventArgs e)
        {
            SetHoaDon(txtKH.Text.Trim(), txtDienThoai.Text.Trim(), dpkNgay.Value);
        }

        private void NewHoaDon(ref HoaDonDTO hoaDon)
        {
            new HoaDonBLL().Insert(hoaDon);
            hoaDon = new HoaDonBLL().GetLast();
        }

        private void CreateChiTiet(HoaDonDTO hoaDon)
        {
            foreach (ChiTietHoaDonDTO chiTiet in dsChiTiet)
            {
                chiTiet.MaHoaDon = hoaDon.MaHoaDon;
            }
            new ChiTietHoaDonBLL().Insert(dsChiTiet);
        }

        private bool checkHoaDon()
        {
            ThamSoDTO thamSo = new ThamSoBLL().GetThamSo();
            int TongGT = 0;
            foreach (ChiTietHoaDonDTO chiTiet in dsChiTiet)
            {
                TongGT += (int)(chiTiet.SoLuong * chiTiet.DonGiaBan * (1 - chiTiet.ChietKhau));
            }
            if (TongGT > thamSo.GTHD)
            {
                MessageBox.Show("Giá trị hóa đơn vượt mức tối đa.", "LỖI", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
            return true;
        }

        private void btnThanhToan_Click(object sender, EventArgs e)
        {
            if (checkHoaDon())
            {
                try
                {
                    NewHoaDon(ref hoaDonTam);
                    CreateChiTiet(hoaDonTam);
                    MessageBox.Show("Lập hóa đơn thành công.", "THÔNG BÁO", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    ResetAll();
                    this.Dispose();
                }
                catch(Exception ex)
                {
                    MessageBox.Show(ex.Message, "LỖI", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                MessageBox.Show("Giá trị hóa đơn quá lớn.", "LỖI", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnXoaTC_Click(object sender, EventArgs e)
        {
            RemoveAll();
            ShowDetail();
            this.Dispose();
        }

        private void txtDienThoai_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!(char.IsControl(e.KeyChar) || char.IsDigit(e.KeyChar)))
            {
                e.Handled = true;
            }
        }
    }
}
